package com.hjimi.ski.utils;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created By 孙岩
 * on 2023/11/15
 */
public class ImageDownloader {
    private static final int THREAD_COUNT = 10;
    private Handler mHandler;
    private ExecutorService mThreadPool;

    public ImageDownloader(Handler handler) {
        this.mHandler = handler;
        this.mThreadPool = Executors.newFixedThreadPool(THREAD_COUNT);
    }

    public void downloadImage(final String url, final String outputPath) {
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String newOutputPath = "";
                    if(url.endsWith(".jpg")||url.endsWith(".png")||url.endsWith(".jpeg")||url.endsWith(".bmp")){
                        newOutputPath = outputPath + ".jpg";
                    }else if(url.endsWith(".mp3")){
                        newOutputPath = outputPath + ".mp3";
                    }
                    Log.d("sunyan","下载的url===="+url);
                    Log.d("sunyan","下载的outputPath===="+outputPath);

                    URL imageUrl = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                    conn.setConnectTimeout(60000); // 1 minute timeout
                    conn.setReadTimeout(60000); // 1 minute timeout
                    conn.setDoInput(true);
                    conn.connect();
                    int responseCode = conn.getResponseCode();
                    if(responseCode == 200) {
                        String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/Pic/app";

                        File dir1 = new File(filePath);
                        if (!dir1.exists()) {
                            dir1.mkdirs();
                        }

                        InputStream is = conn.getInputStream();
                        OutputStream os = new FileOutputStream(newOutputPath);
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) != -1) {
                            os.write(buffer, 0, len);
                        }
                        os.close();
                        is.close();
                        // 在此处调用回调方法，将下载成功的结果传递给主线程
                        mHandler.obtainMessage(1).sendToTarget();
                    } else {
                        // 在此处调用回调方法，将下载失败的结果传递给主线程
                        mHandler.obtainMessage(2).sendToTarget();
                        Log.d("sunyan","下载失败＝＝"+responseCode);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    // 在此处调用回调方法，将异常信息传递给主线程

                    // 在后台线程中发送消息到主线程
                    Message message = Message.obtain();
                    message.what = 3; // 设置消息标识符为0
                    message.obj =  e.toString(); // 设置消息对象为"你好"字符串
                    mHandler.sendMessage(message); // 发送消息到主线程
                }
            }
        });
    }
}
